<?php

namespace App\Http\Middleware;

use App\Http\Config\ErrorCode;
use App\Models\Saas\Mall;
use Closure;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Support\Facades\Response;

class VideoAdminAuthenticate
{
    protected $app;
    public function __construct(Application $app)
    {
        $this->app = $app;
    }

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        /*--- start 跨域测试用 (待删除) ---*/
        header('Access-Control-Allow-Origin: *');                                                                 // 允许任意域名发起的跨域请求
        header('Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE');
        header('Access-Control-Allow-Headers: X-Requested-With,X_Requested_With');
        header('Access-Control-Allow-Headers:x-requested-with,content-type');
        /*--- end 跨域测试用---*/
        if($request->getMethod() == "OPTIONS"){
            return Response::json(["code" => "1", "msg" => "请求错误"], '200', [], JSON_UNESCAPED_UNICODE);
        }
        $request->mallId = $request->mallId && $request->mallId != "undefined" ? $request->mallId : 1; // 后面删除
        if (empty($request->mallId)) {
            return Response::json(["code" => "1", "msg" => "缺少参数mall_id"], '200', [], JSON_UNESCAPED_UNICODE);
        }
        if (!$mallData = Mall::getFields("id,admin_id,manager_id,expired_time,is_delete,is_disable", ["id" => $request->mallId])) {
            return Response::json(ErrorCode::code("customized", "系统不存在"), '200', [], JSON_UNESCAPED_UNICODE);
        }
        if (!empty($mallData["expiredTime"]) && $mallData["expiredTime"] <= time()) {
            return Response::json(ErrorCode::code("mall_expired"), '200', [], JSON_UNESCAPED_UNICODE);
        }
        if ($mallData["isDelete"] != "0") {
            return Response::json(ErrorCode::code("customized", "系统已回收"), '200', [], JSON_UNESCAPED_UNICODE);
        }
        if ($mallData["isDisable"] != "0") {
            return Response::json(ErrorCode::code("customized", "系统已禁用"), '200', [], JSON_UNESCAPED_UNICODE);
        }
        if (!empty($request->manageData) && $mallData["managerId"] != "1" && $mallData["id"] != $request->manageData["mall_id"]) { // 1 - 超级管理员。其它管理员要判断系统的拥有者
            return Response::json(ErrorCode::code("customized", "您无权限操作该系统"), '200', [], JSON_UNESCAPED_UNICODE);
        }
        $request->mallData = $mallData;
        return $next($request);
    }
}
